package com.leetcode.algorithm.y22.m08.w1;

/**
 * 14. 最长公共前缀
 * 
 * https://leetcode.cn/problems/longest-common-prefix/
 * 
 * @author jie.deng
 *
 */
class Question0014Solution01 {
	
	public String longestCommonPrefix(String[] strs) {
		int len = strs.length;
		if (len == 1) {
			return strs[0];
		}
		int idx = 1;
		String prefix = strs[0];
		while (!"".equals(prefix) && idx < len) {
			prefix = longestCommonPrefix(prefix, strs[idx]);
			idx++;
		}
		return prefix;
	}
    
	private String longestCommonPrefix(String str1, String str2) {
		if (str1 == null || "".equals(str1) || str2 == null || "".equals(str2)) {
			return "";
		}
		int len = Math.min(str1.length(), str2.length());
		int idx = 0;
		while (idx < len && str1.charAt(idx) == str2.charAt(idx)) {
			idx++;
		}
		return str1.substring(0, idx);
	}
    
}